package com.avalon.shop.service;

import com.avalon.core.exception.AvalonException;
import com.avalon.core.model.PageParam;
import com.avalon.core.model.RecordRow;
import com.avalon.core.util.BCryptUtil;
import com.avalon.core.util.JacksonUtil;
import com.avalon.core.util.RestTemplateUtils;
import com.avalon.shop.ShopContext;
import com.avalon.shop.config.ShopConfig;
import com.avalon.shop.model.CategoryProductParam;
import com.avalon.shop.model.SearchProductParam;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ProductService {
    private final ShopConfig shopConfig;
    private final ShopContext shopContext;
    private final String serviceMode = "pet.commodity.type";
    private final String petProduct = "pet.commodity";
    private final String productFields = "id,name,price,firstUrl,isHot,isNew,isDiscount," +
            "isRecommend,petCategoryTags.id,petCategoryTags.petBigTypeId.name";

    public ProductService(ShopConfig shopConfig, ShopContext shopContext) {
        this.shopConfig = shopConfig;
        this.shopContext = shopContext;
    }

    /**
     * 首页产品，可以添加查询条件
     */
    public List<Map> getFirstProduct(PageParam pageParam) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", pageParam.getPageNum());
        param.put("pageSize", pageParam.getPageSize());
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/commodity/page",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getFirstProduct错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public List<Map> getCategoryProduct(CategoryProductParam productParam) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("pageNum", productParam.getPageNum());
        param.put("pageSize", productParam.getPageSize());
        param.put("petBigTypeId", productParam.getPetBigTypeId());
        param.put("productCategoryId", productParam.getProductCategoryId());
        param.put("order", productParam.getOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/pet/commodity/category/list",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getCategoryProduct 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }

    public RecordRow getProductOne(Integer id) {
        log.info("getProductOne: id={}", id);
        HashMap<String, Object> param = new HashMap<>();
        param.put("fields", "id,name,price,packaging,isImport,ingredient," +
                "efficacy,weight,brand,storageCondition,productCategoryId.id,productCategoryId.name," +
                "details.id,details.url,details.sequence," +
                "images.id,images.url,images.sequence," +
                "petCategoryTags.id,petCategoryTags.petBigTypeId.name,petCategoryTags.petBigTypeId.id," +
                "isRecommend,isHot,isNew,isDiscount");
        param.put("serviceName", petProduct);
        param.put("rpnCondition", "(=,id," + id + ")");
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        headers.put("token", shopContext.getBackToken());
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/model/get/detail",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            RecordRow recordRow = JacksonUtil.convert2Map(responseEntity.getBody());
            if (recordRow.isEmpty()) {
                throw new AvalonException("产品不存在");
            }
            return recordRow;
        }
        throw new AvalonException("查询产品发生错误");
    }

    public List<Map> getSearchProduct(SearchProductParam searchProductParam) {
        HashMap<String, Object> param = new HashMap<>();
        PageParam pageParam = new PageParam();
        pageParam.setPageNum(searchProductParam.getPageNum());
        pageParam.setPageSize(searchProductParam.getPageSize());
        param.put("page", pageParam);
        param.put("fields", productFields);
        param.put("serviceName", petProduct);
        param.put("rpnCondition", "(like,name," + searchProductParam.getName() + ")");
        param.put("order", searchProductParam.getOrder());
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/model/get/page/condition/object",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            Map map = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<Map>() {
            });
            Object o = map.get("data");
            return (List<Map>) o;
        } else {
            log.error("getCategoryProduct 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }
}
